import storage from '@/utils/storage'
import axiosInstance from '@/utils/request'

export default {
    namespaced: true,
    state: {
        token: localStorage.getItem('token') || '',
        userInfo: storage.get('userInfo')
    },
    mutations: {
        SET_TOKEN(state, token) {
            state.token = token
        },
        SET_USER_INFO(state, userInfo) {
            state.userInfo = userInfo
        }
    },
    actions: {
        clearUserInfo({commit}){
            commit('SET_TOKEN', '')
            commit('SET_USER_INFO', null)
            localStorage.removeItem('token')
            storage.removeKey('userInfo')
            console.log('clearUserInfo');
        },
        getUserInfo({ commit }) {
            // 获取用户信息
            return new Promise(async (resolve, reject) => {
                let userInfo = await axiosInstance({
                    url: '/admin/user/getCurrUserInfo',
                    method: 'post',
                })

                commit('SET_USER_INFO', userInfo)
                storage.set('userInfo', userInfo)
                resolve()
            })
        },
        doLogin({ commit, dispatch }, payload) {
            return new Promise(async (resolve, reject) => {
                try {

                    let formData = new FormData()
                    const { username, password } = payload
                    formData.append("username", username)
                    formData.append("password", password)

                    // 登录
                    let token = await axiosInstance({
                        url: '/login',
                        method: 'Post',
                        data: formData,
                    })
                    commit('SET_TOKEN', token)
                    localStorage.setItem('token', token)

                    await dispatch('getUserInfo')

                    resolve()
                } catch (error) {
                    reject(error)
                }
            })

        },
        doQQLogin({commit,dispatch},payload){
            return new Promise(async (resolve,reject) => {
                try {
                    const {token} = payload
                    commit('SET_TOKEN', token)
                    localStorage.setItem('token', token)
                    await dispatch('getUserInfo')
                    resolve()
                } catch (error) {
                    reject()
                }
            })
        },
        doLogout({commit}) {
            return new Promise(async (resolve, reject) => {
                await axiosInstance({
                    url: '/logout',
                    method: 'Post',
                })
                commit('SET_TOKEN', '')
                commit('SET_USER_INFO', null)

                localStorage.removeItem('token')
                localStorage.removeItem('userInfo')
                resolve()
            })
        }
    },
    getters: {

    }
}